package com.bci.pwtz.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.exception.CanNotDeleteException;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.mysql.dao.DydlfjxMapper;
import com.bci.pwtz.mysql.dao.DypdxMapper;
import com.bci.pwtz.mysql.model.Dydlfjx;
import com.bci.pwtz.mysql.model.Dypdx;
import com.bci.pwtz.service.BusinessRefService;
import com.bci.pwtz.service.CompanyService;
import com.bci.pwtz.service.DydlfjxService;
import com.bci.pwtz.service.DypdxService;
@Service
public class DydlfjxServiceImpl implements DydlfjxService {
	private DydlfjxMapper objMapper;
	private BusinessRefService businessRefService;
	private CompanyService companyService;
	private DypdxMapper dypdxMapper;
	private DypdxService dypdxService;
	private static final Logger _logger=Logger.getLogger(DydlfjxServiceImpl.class);
	public DydlfjxMapper getObjMapper() {
		return objMapper;
	}

	public void setObjMapper(DydlfjxMapper objMapper) {
		this.objMapper = objMapper;
	}

	public CompanyService getCompanyService() {
		return companyService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

	public BusinessRefService getBusinessRefService()
    {
        return businessRefService;
    }

    public void setBusinessRefService(BusinessRefService businessRefService)
    {
        this.businessRefService = businessRefService;
    }

    public DypdxMapper getDypdxMapper()
    {
        return dypdxMapper;
    }

    public void setDypdxMapper(DypdxMapper dypdxMapper)
    {
        this.dypdxMapper = dypdxMapper;
    }

    
    public DypdxService getDypdxService()
    {
        return dypdxService;
    }

    public void setDypdxService(DypdxService dypdxService)
    {
        this.dypdxService = dypdxService;
    }

    @Override
	public Dydlfjx load(String dydlfjxId) throws PwtzDatabaseException {
		if(_logger.isDebugEnabled()){
			_logger.debug("load:dydlfjxId="+dydlfjxId);
		}
		Dydlfjx dydlfjx=null;
		try{
			dydlfjx=objMapper.selectByPrimaryKey(dydlfjxId);
		}catch(DataAccessException e){
			_logger.error(ExceptionUtils.getStackTrace(e));
			throw new PwtzDatabaseException();
		}
		if(dydlfjx!=null){
			_logger.debug("load:result dydlfjx="+dydlfjx.toString());
		}
		return dydlfjx;
	}

	@Override
	public Dydlfjx add(Dydlfjx dydlfjx) throws PwtzDatabaseException {
		if(_logger.isDebugEnabled()){
			_logger.debug("add:dydlfjx="+dydlfjx.toString());
		}
		if(dydlfjx==null){
			if(_logger.isDebugEnabled()){
				_logger.debug("add,dydlfjx is null");
			}
			return null;
		}else{
//			UUID uuid=UUID.randomUUID();
//			dydlfjx.setDeviceid(uuid.toString());
			dydlfjx.setStatus(1);
			dydlfjx.setCreatedate(new Date());
			dydlfjx.setLastmodifiedtime(new Date());
		}
		try{
			objMapper.insertSelective(dydlfjx);
		}catch(DataAccessException e){
			_logger.error(ExceptionUtils.getStackTrace(e));
			throw new PwtzDatabaseException();
		}
		return dydlfjx;
	}

	@Override
	public int delete(String deviceid) throws PwtzDatabaseException,CanNotDeleteException {
		if(_logger.isDebugEnabled()){
			_logger.debug("delete:deviceid="+deviceid);
		}
		int result=0;
		try{
			boolean bl=businessRefService.canDelete("T_DYDLFJX", deviceid);
			if(!bl){
				throw new CanNotDeleteException();
			}
			result=objMapper.deleteById(deviceid,new Date());
		}catch(DataAccessException e){
			_logger.error(ExceptionUtils.getStackTrace(e));
			throw new PwtzDatabaseException();
		}
		return result;
	}

	@Override
	public int update(Dydlfjx dydlfjx) throws PwtzDatabaseException {
		if(_logger.isDebugEnabled()){
			_logger.debug("update:dydlfjx="+dydlfjx.toString());
		}
		int result=0;
		if(dydlfjx==null){
			if(_logger.isDebugEnabled()){
				_logger.debug("update,dydlfjx is null");
			}
			return result;
		}else{
		    dydlfjx.setLastmodifiedtime(new Date());
		}
		try{
			result=objMapper.updateByPrimaryKeySelective(dydlfjx);
		}catch(DataAccessException e){
			_logger.error(ExceptionUtils.getStackTrace(e));
			throw new PwtzDatabaseException();
		}
		return result;
	}

	@Override
	public PaginationList<Dydlfjx> selectDydlfjxs(String devicename,Long companyId,int portalType,String[] medLineCodes,String lineCode,String beginTime,
			String endTime, int pageSize, int pageNo,String currentDeviceId)throws PwtzDatabaseException {
		PaginationList<Dydlfjx> paginationList=new PaginationList<Dydlfjx>();
		if(_logger.isInfoEnabled()){
		    _logger.info("findDybx:|devicename=" + devicename+"|beginTime=" + beginTime+"|endTime=" + endTime+"|companyId="+companyId+"|portalType="+portalType+"|medLineCodes="+PwtzUtils.parseCharacterArrayToString(medLineCodes)+"|lineCode="+lineCode+"|pageSize="+pageSize+"|pageNo="+pageNo);
		}
		List<Dydlfjx> list=null;
		int beginIndex=pageSize*pageNo-pageSize;
		String companyidStr="";
		String [] companyids=null;
		try{
			if(portalType==1){
				companyidStr=companyService.findChildrensId(companyId,null);
				//System.out.println(companyidStr);
				if(companyidStr!=null&&companyidStr.length()>0){
					companyidStr=companyidStr.substring(0, companyidStr.length()-1);
					companyids=companyidStr.split(",");
				}
				//System.out.println(companyids.length);
			}
			list=objMapper.selectDeviceList(devicename,portalType,medLineCodes,lineCode,companyids,companyId,beginTime, endTime, beginIndex, pageSize,currentDeviceId);
		}catch(DataAccessException e){
			_logger.error(ExceptionUtils.getStackTrace(e));
			throw new PwtzDatabaseException();
		}
		if(list!=null){
			_logger.debug("selectDydlfjxs:result list="+list.toString());
		}
		int totalCount = 0;
        int totalPage =1;
        if(pageSize!=0){
            try
            {
                totalCount = objMapper.selectDeviceCount(devicename,portalType,medLineCodes,lineCode,companyids,companyId,beginTime,endTime);
               // System.out.println(totalCount);
            }
            catch (DataAccessException e)
            {
                _logger.error(ExceptionUtils.getStackTrace(e));
                throw new PwtzDatabaseException();
            }
            totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        }else{
            pageNo=1;
            if(list!=null && list.size()>0){
                totalCount = list.size();
            }
        }
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(list);
        paginationList.setTotalRecord(totalCount);
		return paginationList;
	}

    @Override
    public List<Dydlfjx> getSamePreDeviceList(String deviceid) throws PwtzDatabaseException
    {
        List<Dydlfjx> list=null;
        if(_logger.isDebugEnabled()){
            _logger.debug("getSamePreDeviceList : deviceid="+deviceid);
        }
        if(deviceid==null||deviceid==""){
            if(_logger.isDebugEnabled()){
                _logger.debug("getSamePreDeviceList,deviceid is disabled!");
            }
            return list;
        }
        try{
            list=objMapper.getSamePreDeviceList(deviceid);
        }catch(DataAccessException e){
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return list;
    }

    @Override
    public boolean deleteDevice(String deviceid) throws PwtzDatabaseException, CanNotDeleteException
    {
        boolean flag=true;
        if(_logger.isDebugEnabled()){
            _logger.debug("deleteDevice:deviceid="+deviceid);
        }
        if(deviceid==null||deviceid==""){
            if(_logger.isDebugEnabled()){
                _logger.debug("deleteDevice,deviceid is disable");
            }
            return flag=false;
        }
        List<Dydlfjx> list=null;
        int result=0;
        try{
            list=getSamePreDeviceList(deviceid);
            if(list!=null&&list.size()>0){
                for(Dydlfjx device : list){
                    List<Dydlfjx> dlist=getSamePreDeviceList(device.getDeviceid());
                    if(dlist!=null && dlist.size()>0){
                        deleteDevice(device.getDeviceid());
                    }
                    result=delete(device.getDeviceid());
                    if(result==0){
                        flag=false;
                        break;
                    }
                    
                }
            }
            List<Dypdx> dlist=dypdxMapper.getSamePreDeviceList(deviceid);
            if(dlist!=null&&dlist.size()>0){
                for(Dypdx device : dlist){
                    List<Dypdx> ddlist=dypdxMapper.getSamePreDeviceList(device.getDeviceid());
                    if(ddlist!=null && ddlist.size()>0){
                        dypdxService.deleteDevice(device.getDeviceid());
                    }
                    result=dypdxService.delete(device.getDeviceid());
                    if(result==0){
                        flag=false;
                        break;
                    }
                    
                }
            }
        }catch(DataAccessException e){
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return flag;
    }
    @Override
	public int updateLastSyncDevice(Long companyId, String lastSyncTime)  throws PwtzDatabaseException{
		int result=0;
		try {
			result=objMapper.updateLastSyncDevice(companyId, lastSyncTime);
		} catch (DataAccessException e) {
			_logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
		}
		return result;
	}
}
